LMS="192.168.0.120" # Server IP

LMSPORT="9090"
#MYNAME=`uname -n`
MYNAME='Streamer'

count=0
offtime=4
debug=0

while getopts ":d" opt; do
  case $opt in
    d)
      echo "Debugging mode" >&2
      debug=1
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

log(){
                if [ $debug -eq 1 ]; then
                echo $1
		fi
}


init(){
	initialised=1 # placeholder code
	#gpio mode 29 out
	#gpio write 0 1
}

AlsaBound() {
	if grep -q "^closed$" /proc/asound/card1/pcm0p/sub0/status; then
		echo 0
	else
		echo 1
	fi
}

ampOn(){
	log "Switching on amplifier"
	gpio write 29 1
}

ampOff(){
	log "Switching off amplifier"
	gpio write 29 0
}

LMSOff() {
	{
	log "Soft power down player"
	echo $MYNAME power 0
	echo exit
	} | nc $LMS $LMSPORT >/dev/null
}

LMSPlaying(){
if		{
		echo $MYNAME status
		echo exit
		} | nc  $LMS $LMSPORT| sed 's/ /\n/g'|grep "^mode"|grep -q play
		then
			echo 1
		else
			echo 0
		fi 
}

init
while :
	do

	# if Alsa unbound, loop and check Alsa closely
	while [ `AlsaBound` == "0" ]; do
		sleep 0.2
	done

	#If the player is playing, turn on the amp and watch loosely
		while [ `LMSPlaying` == "1" ]; do
		ampOn
		count=0
		sleep 5
		log "Sleeping while playing"

	done

	# if not playing (anymore) wait until offtime is passed
	# checking LMS while waiting
	while [[ `LMSPlaying` == "0" && $count -lt $offtime ]]; do
		count=$((count+1))
		sleep 10
		log "waiting $count"
	done

	# offtime passed, without any attempt to start playing
	# turn off Box and LMS
	if [ $count -ge $offtime ]; then
		ampOff
		sleep 1
		LMSOff
	fi

done
